<?php
namespace App\Services;

use App\Project;
use App\Tools\ExcelTool;
use App\User;
use Illuminate\Support\Facades\DB;

class ExcelExportService {

    private $params = [];

    private $fileName;

    private $filePath;

    private $type;

    private $basePath;

    public function __construct(array $params)
    {
        $this->params = $params;
        $this->type = $params['type'];
        $this->fileName = isset($params['filename']) ? $params['filename'] : '';
        $this->basePath = public_path('storage/excel/');
        if (!is_dir($this->basePath)){
            mkdir($this->basePath, 0777, true);
        }
    }

    /**
     * 导出excel
     * @return array
     * @author: lxy
     * @time: 2020/6/16 11:55 上午
     * @流程:
     */
    public function Export() {
        switch ($this->type){
            case 'list_project':
                $res = $this->exportListProject();
                break;
            case 'assign_review':
                $res = $this->exportReviewGroup();
                break;
            case 'expert_review':
                $res = $this->projectReviewProgress();
                break;
            case 'expert_score':
                $res = $this->projectReviewScore();
                break;
            case 'meeting_review':
                $res = $this->projectMeetingReview();
                break;
            default:
                $res = false;
                break;
        }

        if ($res === true) {
            $result = [
                'ok'        => true,
                'fileName'  => $this->fileName,
                'url'       => asset('storage/excel/'.$this->fileName)
            ];
        } else {
            $result = [
                'ok'    => false,
                'msg'   => $res
            ];
        }

        return $result;
    }


    /**
     * 导出项目信息
     * @return bool|mixed
     * @author: lxy
     * @time: 2020/6/16 11:50 上午
     * @流程:
     */
    private function exportListProject() {
        $columns = [
            '项目ID',
            '申报奖项',
            '项目名称',
            '专业类别',
            '申报者',
            '所在单位',
            '联系电话',
            '联系邮箱',
            '申报书',
            '附件',
            '状态'
        ];
        $awardId = $this->params['award_id'];
        $status_ids = $this->params['status_ids'];
        $statusIds = array_filter(explode(',', $status_ids));
        $largeGroupId = null;
        if (isset($this->params['large_group_id'])
            && $this->params['large_group_id'] > 0) {
            $largeGroupId = $this->params['large_group_id'];
        }

        $data = $this->getPeoject($awardId,$statusIds,$largeGroupId);
        if (empty($data)) {
            return  '没有可导出数据';
        }
        $Excel = new ExcelTool;
        $res = $Excel->Export($data,$columns,$this->getFileName(),['I','J']);
        if ($res !== true) {
            return $Excel->GetMessage();
        }
        return true;
    }


    /**
     * 导出小组信息
     * @return bool|mixed
     * @author: lxy
     * @time: 2020/6/16 11:53 上午
     * @流程:
     */
    private function exportReviewGroup() {
        $largeGroupId = $this->params['large_group_id'];
        $data = (new ReviewerGroupService())->getReviewerGroups($largeGroupId);

        if ($data['code'] != 0) {
            return  $data['msg'];
        }

        if (empty($data['reviewer_groups'])) {
            return '暂无可导出数据';
        }

        $Excel = new ExcelTool;
        $res = $Excel->ExportReviewGroup(
            $data['reviewer_groups'],
            ReviewerGroupService::REVIEWER_GROUP_REVIEWER_COUNT,
            $this->getFileName());

        if ($res !== true) {
            return $Excel->GetMessage();
        }
        return true;
    }

    /**
     * 网评评审进度
     * @return bool|mixed|string
     * @author: lxy
     * @time: 2020/6/16 2:46 下午
     * @流程:
     */
    public function projectReviewProgress(){
        $largeGroupId = $this->params['large_group_id'];
        $data = (new ReviewService())->getReviewerProjectStats($largeGroupId);
        if (empty($data)) {
            return '暂无可导出数据';
        }

        $columns = [
            '小组名称',
            '专家信息',
            '联系电话',
            '未完成项目数',
            '已完成项目数',
            '总项目数',
        ];

        foreach ($data as &$item) {
            $temp = [
                '小组名称' => "({$item['reviewer_group_id']}) {$item['large_group_name']}",
                '专家信息' => "{$item['name']}/$item[prof_title]/{$item['work_org_name']}",
                '联系电话' => $item['tel'],
                '未完成项目数' => $item['unfinished_projects'],
                '已完成项目数' => $item['finished_projects'],
                '总项目数' => $item['total_projects'],
            ];
            $item = $temp;
        }


        $Excel = new ExcelTool;
        $res = $Excel->Export($data, $columns, $this->getFileName());
        if ($res !== true) {
            return $Excel->GetMessage();
        }
        return true;
    }


    /**
     * 网评评分信息
     * @return bool|mixed|string
     * @author: lxy
     * @time: 2020/6/17 7:33 下午
     * @流程:
     */
    public function projectReviewScore() {
        $largeGroupId = $this->params['large_group_id'];
        $data = (new ProjectService())->adminGetExpertReviewProjects($largeGroupId);
        if ($data['code'] != 0 || empty($data['projects'])) {
            return '暂无可导出数据';
        }
        $Excel = new ExcelTool;

        $res = $Excel->ExportProjectReviewScore(
            $data['projects'],
            ReviewerGroupService::REVIEWER_GROUP_REVIEWER_COUNT,
            $this->getFileName());

        if ($res !== true) {
            return $Excel->GetMessage();
        }
        return true;
    }

    public function projectMeetingReview(){
        $largeGroupId = $this->params['large_group_id'];
        $data = (new ProjectService())->leaderGetMeetingReviewProjects($largeGroupId);
        if ($data['code'] != 0 || empty($data['projects'])) {
            return '暂无可导出数据';
        }

        $columns = [
            '项目名次',
            '初始名次',
            '获奖',
            '项目名称',
            '申报者',
            '平均分',
            '会评状态'
        ];
        $excelData = [];
        foreach ($data['projects'] as $val) {
            $excelData[] = [
                $val->meeting_ranking,
                $val->meeting_initial_ranking,
                $val->award,
                $val->project_name,
                $val->applicant_name,
                $val->avg_score,
                $val->meeting_review_status
            ];
        }

        $Excel = new ExcelTool;
        $res = $Excel->Export($excelData, $columns, $this->getFileName());
        if ($res !== true) {
            return $Excel->GetMessage();
        }
        return true;
    }


    /**
     * 获取文件名
     * @return string
     * @author: lxy
     * @time: 2020/6/15 4:00 下午
     * @流程:
     */
    private function getFileName(){
        $fileName = $this->fileName;
        if (empty(trim($fileName))) {
            $this->fileName = date('Y-m-d-').$this->type;
        }

        $this->filePath = $this->basePath.$this->fileName.'.xls';
        return $this->filePath;
    }

    /**
     * list_project 获取项目信息
     * @param int $awardId
     * @param array $statusIds
     * @param null $largeGroupId
     * @return mixed
     * @author: lxy
     * @time: 2020/6/15 2:54 下午
     * @流程:
     */
    private function getPeoject(int $awardId,array $statusIds,$largeGroupId=null){
        $query = DB::table('applications as A')
            ->where('A.award_id', $awardId);
        if (!empty($statusIds)) {
            $query->whereIn('status_id', $statusIds);
        }
        if ($largeGroupId !== null) {
            $query->where('large_group_id', $largeGroupId);
        }

        $query->leftJoin('award_and_expert_group_relations as B', 'A.id', '=', 'B.award_id')
            ->leftJoin('application_groups as C', 'B.award_group_id', '=', 'C.id')
            ->orderBy('A.submitted_at', 'asc')
            ->select('A.id', 'A.award_id', 'A.project_name', 'A.user_id', 'A.status_id', 'A.status_remarks', 'A.prof_category', 'B.expert_group_id', 'C.group_name', 'A.pdf_file_save_path', 'A.large_group_id');
        $projects = $query->get();


        $applicantIds = $projects->map(function ($record) {
            return $record->user_id;
        })->unique();
        $applicants = User::whereIn('id', $applicantIds)
            ->select('id', 'name', 'work_org_name', 'tel', 'email')
            ->get();
        $applicantMap = [];
        foreach ($applicants as $applicant) {
            $applicantMap[$applicant->id] = $applicant;
        }

        $result = [];
        $award_id_txt = [
            1 => '进步奖',
            2 => '科技人物奖'
        ];
        foreach ($projects as $project) {
            if (empty($project->nominator_ids)) {
                $project->nominator_ids = [];
            } else {
                $project->nominator_ids = explode(',', $project->nominator_ids);
            }
            $applicant = $applicantMap[$project->user_id];
//            $project->applicant_name = $applicant->name;
//            $project->applicant_org_name = $applicant->work_org_name;
//            $project->applicant_tel = $applicant->tel;
//            $project->applicant_email = $applicant->email;
            $project->status_info = (new AwardService())->getStatusDef($project->status_id);
            $result[] = [
                '项目ID'   => $project->id,
                '申报奖项'  => $award_id_txt[$project->award_id],
                '项目名称'  => $project->project_name,
                '专业类别'  => $project->prof_category,
                '申报者'    => $applicant->name,
                '所在单位'  => $applicant->work_org_name,
                '联系电话'  => $applicant->tel,
                '联系邮箱'  => $applicant->email,
                '申报书'    => env('APP_URL').'/home/view-form?id='.$project->id,
                '附件'      => env('APP_URL').'/home/view-attachments?project_id='.$project->id,
                '状态'      => $project->status_info['phase'].'-'.$project->status_info['status']
            ];
        }
        return $result;
    }

}
